package com.geekbing.elklog.config;

import com.alibaba.fastjson.JSON;
import com.geekbing.elklog.util.response.Result;
import com.geekbing.elklog.util.response.ResultCode;
import com.geekbing.elklog.util.response.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局异常处理
 *
 * @author bing
 */
@ControllerAdvice
public class GlobalExceptionResolver {
    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionResolver.class);

    /**
     * 业务异常的处理
     */
    @ExceptionHandler(value = ServiceException.class)
    public void serviceExceptionHandler(HttpServletResponse response, ServiceException e) {
        Result result = Result.build().setCode(e.getCode()).setMessage(e.getMessage());
        responseResult(response, result);
    }

    /**
     * 其他异常统一处理
     */
    @ExceptionHandler(value = Exception.class)
    public void exceptionHandler(HttpServletResponse response) {
        Result result = Result.build().setCode(ResultCode.INTERNAL_SERVER_ERROR).setMessage("服务器打酱油了，请稍后再试~");
        responseResult(response, result);
    }

    private void responseResult(HttpServletResponse response, Result result) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.setStatus(result.getCode().getCode());
        try {
            response.getWriter().write(JSON.toJSONString(result));
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }
}
